package com.hdu;

import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.concurrent.locks.LockSupport;

public class PrintProblem {


    public static void main(String[] args) {
        print2();
    }

    /**
     * 打印
     * a1b2c3d4e5f6g7h8i9j10k11l12m13n14o15p16q17r18s19t20u21v22w23x24y25z
     */
    public static void print1() {
        Printer printNum = new Printer();
        Printer printChar = new Printer();

        printNum.setPrintable(
                () -> {
                    for (int i = 0; i < 26; i++) {
                        LockSupport.park(printNum);
                        System.out.print(i + " ");
                        LockSupport.unpark(printChar);
                    }
                }
        );

        printChar.setPrintable(
                () -> {
                    for (char i = 'a'; i <= 'z'; i++) {
                        LockSupport.park(printChar);
                        System.out.println(i + " ");
                        LockSupport.unpark(printNum);
                    }
                }
        );

        printNum.start();
        printChar.start();

        LockSupport.unpark(printNum);
    }


    /**
     * 交替打印奇偶数
     */
    public static void print2() {
        Printer printJi = new Printer();
        Printer printOu = new Printer();

        printJi.setPrintable(
                () -> {
                    for (int i = 1; i <= 100; i += 2) {
                        LockSupport.park(printJi);
                        System.out.println(i);
                        LockSupport.unpark(printOu);
                    }
                }
        );

        printOu.setPrintable(
                () -> {
                    for (int i = 2; i <= 100; i += 2) {
                        LockSupport.park(printOu);
                        System.out.println(i);
                        LockSupport.unpark(printJi);
                    }
                }
        );

        printJi.start();
        printOu.start();

        LockSupport.unpark(printJi);
    }

}


@NoArgsConstructor
class Printer extends Thread {


    @Setter
    private Printable printable;

    @Override
    public void run() {
        printable.print();
    }
}

@FunctionalInterface
interface Printable {
    void print();
}